#!/bin/sh

root_path=`pwd`
root_file=$1

function build_mysql() {
    cd $1/$2/model
    echo "#! /bin/bash" >> build_mysql.sh
    echo "goctl model mysql ddl -src ${2}.sql -dir . -c" >> build_mysql.sh
}

function build_api() {
    cd $1/$2/cmd/api
    echo "#! /bin/bash" >> build_api.sh
    echo "goctl api go -api ${2}.api -dir ." >> build_api.sh
}

function build_proto() {
    cd $1/$2/cmd/rpc
    goctl rpc template -o=$2.proto
    sed -i "4s/.*/option go_package =\".\/${2}\"/" $1/$2/cmd/rpc/$2.proto
    echo "#! /bin/bash" >> build_proto.sh
    echo "goctl rpc protoc ${2}.proto --go_out=. --go-grpc_out=. --zrpc_out=." >> build_proto.sh
}

if [ ! -d $root_file ]
then
  mkdir $root_file && cd $root_file
  go mod init $root_file
  mkdir common apps deplay doc dbs
fi

for key in $*
do
  echo $root_path $root_file $key
  if [ $key == $root_file ]
  then
    cd $root_path/$key
    cp $root_path/dbs/* $root_path/$key/dbs/
  else
    app_file=$root_path/$root_file/apps
    cd $app_file
    if [ ! -d $app_file/$key ]
    then
      mkdir -p $key/cmd $key/model $key/cmd/rpc
      build_api $app_file $key
      build_proto $app_file $key
      build_mysql $app_file $key
    fi
  fi
done